﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Orion.Lib;
using System.Xml.Linq;
using System.Reflection;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MainLevelPack
{
    public class LevelProvider 
        : ILevelProvider
    {
        static Microsoft.Xna.Framework.Content.ContentManager cm;
        public LevelProvider(Game game)
        {
            cm = new Microsoft.Xna.Framework.Content.ContentManager(game.Services, "MainLevelPackContent");
        }


        private static List<LevelDescriptor> LoadLevelList(ILevelProvider providerInstance)
        {
            var result = new List<LevelDescriptor>();
            var manifest = XDocument.Load(Assembly.GetCallingAssembly().GetManifestResourceStream("MainLevelPack.LevelManifest.xml"));

            var levelsNodes = from l in manifest.Root.Element("Levels").Elements() select l;
          
            foreach (var node in levelsNodes)
            {
                result.Add(new LevelDescriptor() { 
                        Name = node.Attribute("name").Value,
                        Index = int.Parse(node.Attribute("index").Value),
                        icon = string.IsNullOrEmpty(node.Attribute("icon").Value)?null: cm.Load<Texture2D>(node.Attribute("icon").Value),
                        frameFile = node.Attribute("frameFile").Value,
                        category = node.Attribute("category").Value,
                        provider = providerInstance
                });
            }

            return result;
        }

        #region ILevelProvider Members

        public List<LevelDescriptor> GetLevels(ILevelProvider providerInstance)
        {
            return LoadLevelList(providerInstance);
        }

        public string GetProviderName
        {
            get { return "MainLevelsProvider"; }
        }

        public string GetProviderVersion
        {
            get { return "Beta"; }
        }

        public XDocument GetLevelFile(LevelDescriptor ld)
        {
            return LoadFile(ld.frameFile);
        }

        private XDocument LoadFile(string p)
        {
            return XDocument.Load(Assembly.GetCallingAssembly().GetManifestResourceStream(p));
        }

        #endregion
    }
}
